<template>
  <div class="report-form">
    <div class="report-form-content">
      <div class="report-form-content-title">
        <h1 style="font-weight: bold" v-if="oper === 'add'">新增预算指标单</h1>
        <h1 style="font-weight: bold" v-if="oper === 'edit'">修改预算指标单</h1>
        <h1 style="font-weight: bold" v-if="oper === 'view'">查看预算指标单</h1>
      </div>
      <div style="text-align: right;">
        <div class="tabs-list">
          <el-button type="success" @click="handleSave">
            <svg-icon icon-class="save" />
            保存
          </el-button>
          <el-button v-show="checkAuthByCode('')" type="primary" @click="handleSubmit" v-if="obj.id">
            <svg-icon icon-class="submit" />
            提交审批
          </el-button>
        </div>
      </div>
      <div>
        <el-tabs v-model="activeName" class="demo-tabs">
          <el-tab-pane label="预算指标单录入" name="1"></el-tab-pane>
          <el-tab-pane label="经济支出预算" name="2" v-if="obj.isEconomic === '1'"></el-tab-pane>
        </el-tabs>
        <div class="tabs-list" v-show="activeName === '1'">
          <el-form class="my-form" ref="objForm" :model="obj" :rules="rules" label-position="right" label-width="auto" label-suffix="：" :disabled="oper === 'view'">
            <el-row :gutter="20">
              <el-col :sm="24" :lg="24" style="padding-left: 20px">
                <el-card class="update-log">
                  <div class="report-form-list-content">
                    <el-form-item label="日期" prop="kpiDate" class="item">
                      <el-date-picker v-model="obj.kpiDate" type="date" placeholder="请选择" value-format="YYYY-MM-DD" />
                    </el-form-item>
                    <el-form-item label="预算年度" prop="year">
                      <el-date-picker v-model="obj.year" type="year" placeholder="请选择" value-format="YYYY" />
                    </el-form-item>
                    <el-divider />
                    <el-form-item label="指标单编码" prop="kpiCode">
                      <el-input v-model="obj.kpiCode" placeholder="指标单编码" />
                    </el-form-item>
                    <el-form-item label="指标名称" prop="kpiName">
                      <el-input v-model="obj.kpiName" placeholder="指标名称" />
                    </el-form-item>
                    <el-form-item label="支出类型" prop="payType">
                      <el-select v-model="obj.payType" class="m-2" placeholder="请选择">
                        <el-option v-for="item in getDictList('ExpenditureKpiPayType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="经费类型" prop="fundType">
                      <el-select v-model="obj.fundType" class="m-2" placeholder="请选择">
                        <el-option v-for="item in getDictList('ExpenditureKpiFundType')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="项目负责人部门" prop="organizationId">
                      <Organization v-model="obj.organizationId" keyName="id" keyShow="organizationName" placeholder="项目负责人部门" title="部门查询" />
                    </el-form-item>
                    <el-form-item label="项目负责人用户" prop="managerId">
                      <User v-model="obj.managerId" keyName="id" keyShow="name" placeholder="项目负责人用户" title="用户查询" />
                    </el-form-item>
                    <el-form-item label="项目类型" prop="expenditurePtypeId">
                      <el-cascader v-model="obj.expenditurePtypeId" :options="arrChangeTreeFn(expenditurePtypeList)" :props="{label: 'name', value: 'id'}" :show-all-levels="false" clearable filterable>
                        <template #default="{ data }">
                          <span>{{ data.code }}</span>
                          <span style="padding: 0 5px">-</span>
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                    <el-form-item label="功能分类" prop="expenditureFunctionalId">
                      <el-cascader v-model="obj.expenditureFunctionalId" :options="arrChangeTreeFn(expenditureFunctionalList)" :props="{label: 'name', value: 'id'}" :show-all-levels="false" clearable filterable>
                        <template #default="{ data }">
                          <span>{{ data.code }}</span>
                          <span style="padding: 0 5px">-</span>
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </div>
                  <div class="report-form-list-content-1">
                    <el-form-item label="财政项目" prop="expenditureFiscalId">
                      <el-cascader v-model="obj.expenditureFiscalId" :options="arrChangeTreeFn(expenditureFiscalList)" :props="{label: 'name', value: 'id'}" :show-all-levels="false" clearable filterable style="width: 600px;">
                        <template #default="{ data }">
                          <span>{{ data.code }}</span>
                          <span style="padding: 0 5px">-</span>
                          <span>{{ data.name }}</span>
                        </template>
                      </el-cascader>
                    </el-form-item>
                  </div>
                  <div class="report-form-list-content">
                    <el-form-item label="指标来源" prop="source">
                      <el-select v-model="obj.source" class="m-2" placeholder="请选择">
                        <el-option v-for="item in getDictList('ExpenditureKpiSource')" :key="item.key" :label="`${item.key} - ${item.value}`" :value="item.key" />
                      </el-select>
                    </el-form-item>
                    <el-form-item label="预算总金额" prop="amount">
                      <el-input-number v-model="obj.amount" placeholder="请输入预算总金额" :min="0" :precision="2" :disabled="obj.isEconomic === '1'" />
                    </el-form-item>
                    <el-form-item label="按经济分类控制金额" prop="isEconomic">
                      <el-radio-group v-model="obj.isEconomic" @change="changeIsEconomic">
                        <el-radio-button v-for="(item,index) in getEnumList('CommonYesNo')" :label="item.key" :key="index">{{item.value}}</el-radio-button>
                      </el-radio-group>
                    </el-form-item>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-form>
          <el-divider />
        </div>
        <div class="tabs-list" v-show="activeName === '2'">
          <div class="" style="display: flex;align-items: center;justify-content: space-between;">
            <el-button type="primary" icon="Plus" style="margin-left:20px" @click="addItem">新增</el-button>
            <div style="font-weight: bold; color: brown;">合计：￥{{ totalAmount }}</div>
          </div>
          <el-divider />
          <div class="report-form-list-content" v-for="(item,index) in items" :key="index">
            <el-form class="my-form" ref="subObjForm" :model="item" :rules="subRules" label-position="right" label-width="auto" label-suffix="：" :disabled="oper === 'view'">
              <label class="form-label">经济支出预算{{ index + 1 }}:</label>
              <el-card class="update-log update-log-1">
                <div class="report-form-list-content">
                  <el-form-item label="经济分类" prop="expenditureEconomicId">
                    <el-cascader v-model="item.expenditureEconomicId" :options="arrChangeTreeFn(expenditureEconomicList)" :props="{label: 'name', value: 'id'}" :show-all-levels="false" clearable filterable @change="expenditureEconomicChange($event,index)" />
                  </el-form-item>
                  <el-form-item label="金额" prop="amount">
                    <el-input-number v-model="item.amount" placeholder="请输入金额" :min="0" :precision="2" />
                  </el-form-item>
                  <el-form-item label="浮动率(上浮百分比)" prop="fluctuate">
                    <el-input-number v-model="item.fluctuate" placeholder="请输入浮动率" :min="0" :precision="0" />%
                  </el-form-item>
                </div>
                <div class="report-form-list-content-1">
                  <el-form-item label="备注">
                    <el-input v-model="item.remark" :autosize="{ minRows: 2, maxRows: 5}" type="textarea" class="textarea-1" />
                  </el-form-item>
                </div>
                <div class="form-list-content-1">
                  <div class="" style="width: 100%">
                    <el-button class="ico-list" icon="Delete" type="danger" v-if="index >= 1" @click="removeItem(index)">删除</el-button>
                  </div>
                </div>
              </el-card>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <selectApprove v-model:itemsVisible="dialogApproveVisible" @close="dialogApproveVisible = false" :business="'2001'" :businessId="obj.id" @doSubmit="doSubmit" />
  </div>
</template>

<script>
import baseConfig from '@/mixins/baseConfig'
import {doGet, doPost} from '@/config/http'
import {
  alertErrorMsg,
  customValidator,
  notifySuccess,
  arrChangeTreeFn,
  getListPageSize,
  svc,
  initListUpdate
} from '@/config/common'
import {parseTime} from "@/utils/ruoyi";
import {getUserId} from "@/config/cookie";
import useUserStore from "@/store/modules/user";
import User from "@/views/components/base/selectUser.vue";
import Organization from "@/views/components/base/selectOrganization.vue";
import selectApprove from "@/views/components/base/selectApprove.vue";
import initListStore from '@/store/modules/initList'

const emptyObj = {
  kpiCode: null, // 指标编码
  kpiName: null, // 指标名称
  kpiDate: parseTime(new Date().getTime(), '{y}-{m}-{d}'), // 单据日期
  year: parseTime(new Date().getTime(), '{y}'), // 预算年度
  payType: null, // 支出类型
  fundType: null, // 经费类型
  amount: 0, // 预算总金额
  expenditurePtypeId: null, // 项目类型ID
  expenditureFunctionalId: null, // 功能分类ID
  expenditureFiscalId: null, // 财政项目ID
  source: null, // 指标来源
  organizationId: useUserStore().organization.id, // 项目负责人部门ID
  managerId: getUserId(), // 项目负责人用户ID
  state: null, // 状态
  isEconomic: '0', // 按经济分类控制金额
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
  approveId: null
}

const emptyItem = {
  expenditureKpiId: null, // 指标单表ID
  expenditureEconomicId: null, // 经济分类ID
  amount: 0, // 金额
  fluctuate: 0, // 浮动率
  remark: null, // 备注
  id: null,
  createBy: null,
  createTime: null,
  updateBy: null,
  updateTime: null,
  deleted: null,
  version: null,
}

export default {
  name: 'expenditureKpiEdit_nocache',
  components: {
    Organization,
    User,
    selectApprove,
  },
  mixins: [baseConfig],
  data() {
    return {
      obj: Object.assign({}, emptyObj),
      routes: [],
      oper: null,
      id: null,
      objForm: null,
      subObjForm: null,
      activeName: '1',
      items: [ Object.assign({}, emptyItem) ],
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: false,
      rules: {
        kpiCode: [{ required: true, validator: customValidator, min: 0, max: 100, label: '指标编码', trigger: ['blur', 'change'] }],
        kpiName: [{ required: true, validator: customValidator, min: 0, max: 200, label: '指标名称', trigger: ['blur', 'change'] }],
        kpiDate: [{ required: true, validator: customValidator, min: 0, max: 100, label: '单据日期', trigger: ['blur', 'change'] }],
        year: [{ required: true, validator: customValidator, min: 0, max: 4, label: '预算年度', trigger: ['blur', 'change'] }],
        payType: [{ required: true, validator: customValidator, min: 0, max: 100, label: '支出类型', trigger: ['blur', 'change'] }],
        fundType: [{ required: true, validator: customValidator, min: 0, max: 100, label: '经费类型', trigger: ['blur', 'change'] }],
        expenditurePtypeId: [{ required: true, validator: customValidator, min: 0, max: 100, label: '项目类型ID', trigger: ['blur', 'change'] }],
        expenditureFunctionalId: [{ required: true, validator: customValidator, min: 0, max: 100, label: '功能分类ID', trigger: ['blur', 'change'] }],
        expenditureFiscalId: [{ required: true, validator: customValidator, min: 0, max: 100, label: '财政项目ID', trigger: ['blur', 'change'] }],
        source: [{ required: true, validator: customValidator, min: 0, max: 100, label: '指标来源', trigger: ['blur', 'change'] }],
        amount: [{ required: true, validator: customValidator, min: 0, minValue: 1, max: 13, label: '预算总金额', trigger: ['blur', 'change'] }],
        organizationId: [{ required: true, validator: customValidator, min: 0, max: 100, label: '项目负责人部门ID', trigger: ['blur', 'change'] }],
        managerId: [{ required: true, validator: customValidator, min: 0, max: 100, label: '项目负责人用户ID', trigger: ['blur', 'change'] }],
        state: [{ required: false, validator: customValidator, min: 0, max: 20, label: '状态', trigger: ['blur', 'change'] }],
        isEconomic: [{ required: true, validator: customValidator, min: 0, max: 20, label: '按经济分类控制金额', trigger: ['blur', 'change'] }],
      },
      subRules: {
        expenditureEconomicId: [{ required: true, validator: customValidator, min: 0, max: 13, label: '经济分类', trigger: ['blur', 'change'] }],
        amount: [{ required: true, validator: customValidator, min: 0, max: 13, label: '金额', trigger: ['blur', 'change'] }],
        fluctuate: [{ required: true, validator: customValidator, min: 0, max: 13, label: '浮动率', trigger: ['blur', 'change'] }],
      },
      governmentList: initListStore().governmentList,
      organizationList: initListStore().organizationList,
      userList: initListStore().userList,
      expenditurePtypeList: initListStore().expenditurePtypeList,//项目类型
      expenditureFunctionalList: initListStore().expenditureFunctionalList,//功能分类
      expenditureEconomicList:initListStore().expenditureEconomicList,//经济分类
      expenditureFiscalList: initListStore().expenditureFiscalList,//财政项目
      expenditureSubjectList: initListStore().expenditureSubjectList,//会计科目
      dialogApproveVisible: false,
      approveList: [],
      selectExpenditureEconomicIds: [],
    }
  },
  computed: {
    routesData() {
      return this.routes
    },
    totalAmount() {
      let total = 0
      this.items.forEach(item => total += parseFloat(item.amount))
      if (this.obj.isEconomic === '1')
        this.obj.amount = total
      return total
    },
  },
  created() {
    this.initObj()
    // this.initList()
  },
  methods: {
    arrChangeTreeFn,
    // async initList() {
    //   let p1 = doGet(svc, '/government/page', {pageSize: getListPageSize()}, false)
    //   let p2 = doGet(svc, '/organization/page', {pageSize: getListPageSize()}, false)
    //   let p3 = doGet(svc, '/user/page', {pageSize: getListPageSize()}, false)
    //   let p4 = doGet(svc, '/expenditure-ptype/page', {pageSize: getListPageSize()}, false)
    //   let p5 = doGet(svc, '/expenditure-functional/page', {pageSize: getListPageSize()}, false)
    //   let p6 = doGet(svc, '/expenditure-economic/page', {pageSize: getListPageSize()}, false)
    //   let p7 = doGet(svc, '/expenditure-fiscal/page', {pageSize: getListPageSize()}, false)
    //   let p8 = doGet(svc, '/expenditure-subject/page', {pageSize: getListPageSize()}, false)
    //   let resArray = await Promise.all([p1, p2, p3, p4, p5, p6, p7, p8])
    //   this.governmentList = resArray[0]['records']
    //   this.organizationList = resArray[1]['records']
    //   this.userList = resArray[2]['records']
    //   this.expenditurePtypeList = resArray[3]['records']
    //   this.expenditureFunctionalList = resArray[4]['records']
    //   this.expenditureEconomicList = resArray[5]['records']
    //   this.expenditureFiscalList = resArray[6]['records']
    //   this.expenditureSubjectList = resArray[7]['records']
    // },
    async initObj() {
      this.oper = this.$route.query.oper
      this.id = null
      if (this.oper !== 'add' && this.$route.query.id) {
        this.id = this.$route.query.id
        this.obj = await doGet(svc, `/expenditure-kpi/${this.id}`, {}, true)
        this.obj.expenditurePtypeId = this.obj.expenditurePtypeId?.split(',')
        this.obj.expenditureFunctionalId = this.obj.expenditureFunctionalId?.split(',')
        this.obj.expenditureFiscalId = this.obj.expenditureFiscalId?.split(',')
        this.items = await doGet(svc, '/expenditure-kpi-item/listByField', {field: 'expenditureKpiId', values: this.id}, false)
        this.items.map(item => {
          item.expenditureEconomicId = item.expenditureEconomicId.split(',')
          this.selectExpenditureEconomicIds.push(item.expenditureEconomicId.join(','))
        })
      }
    },
    async checkForm() {
      const formName = 'objForm'
      let v = await this.$refs[formName].validate().catch((err)=>{return err})
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return false
      }
      let subs = this.$refs['subObjForm']
      for (let idx in subs) {
        let v2 = await subs[idx].validate().catch((err)=>{return err})
        if (v2 !== true) {
          alertErrorMsg('经济支出预算表单验证不通过，请检查数据。')
          return false
        }
      }
      return true
    },
    async handleSave() {
      let v = await this.checkForm()
      if (v !== true)
        return
      if (this.obj.isEconomic === '1' && this.obj.amount !== this.totalAmount) {
        alertErrorMsg('经济支出合计金额[' + this.totalAmount + ']不等于指标单的预算总金额[' + this.obj.amount + ']')
        return
      }
      let o = this.buildObj()
      doPost(svc, '/customExpenditureKpis/saveExpenditureKpi', o, true).then(() => {
        notifySuccess('保存成功')
        this.goTargetByName('expenditureKpi', {}, true)
        this.dialogViewVisible = false
      })
    },
    async handleSubmit() {
      let v = await this.checkForm()
      if (v !== true) {
        alertErrorMsg('表单验证不通过，请检查数据。')
        return
      }
      let o = this.buildObj()
      doPost(svc, '/customExpenditureKpis/saveExpenditureKpi', o, false).then(res => {
        this.obj.id = res['id']
        this.obj.version = res['version']
        this.items.map(item => {
          item.expenditureEconomicId = item.expenditureEconomicId.split(',')
          this.selectExpenditureEconomicIds.push(item.expenditureEconomicId.join(','))
        })
        this.dialogApproveVisible = true
      })
    },
    async doSubmit(data) {
      let v = await this.checkForm()
      if (v !== true)
        return
      let o = this.buildObj()
      o.approveId = data.approveId
      o.approveNodes = data.approveNodes
      doPost(svc, '/customExpenditureKpis/submitExpenditureKpi', o).then(() => {
        notifySuccess('操作成功')
        initListUpdate('expenditureKpiList', '/expenditure-kpi/page')
        this.goTargetByName('expenditureKpi', {}, true)
        this.dialogViewVisible = false
      })
    },
    buildObj() {
      let o = this.obj
      this.obj.expenditurePtypeId = this.obj.expenditurePtypeId instanceof Array ? this.obj.expenditurePtypeId.join(',') : this.obj.expenditurePtypeId
      this.obj.expenditureFunctionalId = this.obj.expenditureFunctionalId instanceof Array ? this.obj.expenditureFunctionalId.join(',') : this.obj.expenditureFunctionalId
      this.obj.expenditureFiscalId = this.obj.expenditureFiscalId instanceof Array ? this.obj.expenditureFiscalId.join(',') : this.obj.expenditureFiscalId
      //items
      o.items = []
      o.items = this.items.map(item => {
        if (item.itemType && typeof(item.itemType) === 'object' && item.itemType.length > 0) {
          item.itemType = item.itemType[1]
        }
        item.expenditureEconomicId = item.expenditureEconomicId instanceof Array ? item.expenditureEconomicId.join(',') : item.expenditureEconomicId
        return item
      })
      return o
    },
    // 新增行
    addItem() {
      let item = Object.assign({}, emptyItem)
      this.items.push(item)
    },
    // 删除行
    removeItem(index) {
      this.items.splice(index, 1)
    },
    changeIsEconomic(v) {
      switch (v) {
        case '0':
          this.items = []
          break;
        case '1':
          this.addItem()
          break;
      }
    },
    expenditureEconomicChange(val,index) {
      let idStr = val.join(',')
      let isHaveIds = this.selectExpenditureEconomicIds.some(item => item === idStr)
      if (isHaveIds) {
        this.items[index].expenditureEconomicId = []
        alertErrorMsg('经济分类不可重复使用，请重新选择。')
      }
      this.selectExpenditureEconomicIds = []
      this.items.map(item => {
        this.selectExpenditureEconomicIds.push(item.expenditureEconomicId.join(','))
      })
    },
  }
}
</script>
<style scoped>
.report-form {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: #fff;
  z-index: 10;
  padding: 20px;
  overflow-x: hidden;
  overflow-y: auto;
}
.report-form-content-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.form-label {
  display: inline-flex;
  justify-content: flex-end;
  align-items: flex-start;
  flex: 0 0 auto;
  font-size: 16px;
  color: #337ecc;
  height: 32px;
  line-height: 32px;
  padding: 0 12px 0 0;
  box-sizing: border-box;
  width: 200px;
  font-weight: bold;
}
.update-log {
  width: 100%;
  margin: 30px 0;
}
.update-log-1 {
  margin-top: 0;
}
</style>
